package archive

import (
	"encoding/json"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/archive"
	archiveReq "github.com/flipped-aurora/gin-vue-admin/server/model/archive/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/example"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/datatypes"
)

type ArchiveFileApi struct {
}

var archiveFileService = service.ServiceGroupApp.ArchiveServiceGroup.ArchiveFileService
var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService

// CreateArchiveFile 创建档案文件
// @Tags ArchiveFile
// @Summary 创建档案文件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body archive.ArchiveFile true "创建档案文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /archiveFile/createArchiveFile [post]
func (archiveFileApi *ArchiveFileApi) CreateArchiveFile(c *gin.Context) {
	var r archiveReq.CreateArchiveFile
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	archiveFile := &archive.ArchiveFile{TypeId: r.TypeId, LocationId: r.LocationId, Name: r.Name, File: r.File, CreatedBy: utils.GetUserID(c)}
	if err := archiveFileService.CreateArchiveFile(archiveFile); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteArchiveFile 删除档案文件
// @Tags ArchiveFile
// @Summary 删除档案文件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body archive.ArchiveFile true "删除档案文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /archiveFile/deleteArchiveFile [delete]
func (archiveFileApi *ArchiveFileApi) DeleteArchiveFile(c *gin.Context) {
	ID := c.Query("ID")
	userID := utils.GetUserID(c)
	if err := archiveFileService.DeleteArchiveFile(ID, userID); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteArchiveFileByIds 批量删除档案文件
// @Tags ArchiveFile
// @Summary 批量删除档案文件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /archiveFile/deleteArchiveFileByIds [delete]
func (archiveFileApi *ArchiveFileApi) DeleteArchiveFileByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	userID := utils.GetUserID(c)
	if err := archiveFileService.DeleteArchiveFileByIds(IDs, userID); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateArchiveFile 更新档案文件
// @Tags ArchiveFile
// @Summary 更新档案文件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body archive.ArchiveFile true "更新档案文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /archiveFile/updateArchiveFile [put]
func (archiveFileApi *ArchiveFileApi) UpdateArchiveFile(c *gin.Context) {
	var r archiveReq.UpdateArchiveFile
	err := c.ShouldBindJSON(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	archiveFile := archive.ArchiveFile{TypeId: r.TypeId, LocationId: r.LocationId, Name: r.Name, File: r.File, UpdatedBy: utils.GetUserID(c)}
	archiveFile.ID = r.ID
	if err := archiveFileService.UpdateArchiveFile(archiveFile); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindArchiveFile 用id查询档案文件
// @Tags ArchiveFile
// @Summary 用id查询档案文件
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query archive.ArchiveFile true "用id查询档案文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /archiveFile/findArchiveFile [get]
func (archiveFileApi *ArchiveFileApi) FindArchiveFile(c *gin.Context) {
	ID := c.Query("ID")
	if rearchiveFile, err := archiveFileService.GetArchiveFile(ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"rearchiveFile": rearchiveFile}, c)
	}
}

// GetArchiveFileList 分页获取档案文件列表
// @Tags ArchiveFile
// @Summary 分页获取档案文件列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query archiveReq.ArchiveFileSearch true "分页获取档案文件列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /archiveFile/getArchiveFileList [get]
func (archiveFileApi *ArchiveFileApi) GetArchiveFileList(c *gin.Context) {
	var pageInfo archiveReq.ArchiveFileSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := archiveFileService.GetArchiveFileInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}

// GetArchiveFilePublic 不需要鉴权的档案文件接口
// @Tags ArchiveFile
// @Summary 不需要鉴权的档案文件接口
// @accept application/json
// @Produce application/json
// @Param data query archiveReq.ArchiveFileSearch true "分页获取档案文件列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /archiveFile/getArchiveFilePublic [get]
func (archiveFileApi *ArchiveFileApi) GetArchiveFilePublic(c *gin.Context) {
	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的档案文件接口信息",
	}, "获取成功", c)
}

// AutoCreateArchiveFile 不需要鉴权的档案文件接口
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /archiveFile/AutoCreateArchiveFile [post]
func (archiveFileApi *ArchiveFileApi) AutoCreateArchiveFile(c *gin.Context) {

	var r archiveReq.AutoCreateArchiveFile
	err := c.ShouldBind(&r)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 判断类型是否存在
	archiveType, err := archiveTypeService.GetArchiveTypeByName(r.TypeName)
	if err != nil {
		archiveType.Name = r.TypeName
		err := archiveTypeService.CreateArchiveType(&archiveType)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	}

	// 判断位置是否存在
	location, err := archiveLocationService.GetArchiveLocationByName(r.LocationName)
	if err != nil {
		location.Name = r.LocationName
		err = archiveLocationService.CreateArchiveLocation(&location)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	}

	// 上传文件
	var file example.ExaFileUploadAndDownload
	noSave := "1"
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
		response.FailWithMessage("接收文件失败", c)
		return
	}
	file, err = fileUploadAndDownloadService.UploadFile(header, noSave) // 文件上传后拿到文件路径

	var m = make([]map[string]string, 1)
	m[0] = make(map[string]string)
	m[0]["url"] = file.Url
	m[0]["name"] = file.Name

	var jsonData datatypes.JSON
	bytesData, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(bytesData, &jsonData)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	archiveFile, err := archiveFileService.GetArchiveFileByName(r.ArchiveName)
	if err != nil {
		typeId := int(archiveType.ID)
		archiveFile.TypeId = &typeId
		locationId := int(location.ID)
		archiveFile.LocationId = &locationId
		archiveFile.Name = r.ArchiveName
		archiveFile.File = jsonData
		err = archiveFileService.CreateArchiveFile(&archiveFile)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	} else {
		typeId := int(archiveType.ID)
		archiveFile.TypeId = &typeId
		locationId := int(location.ID)
		archiveFile.LocationId = &locationId
		archiveFile.Name = r.ArchiveName
		archiveFile.File = jsonData
		err := archiveFileService.UpdateArchiveFile(archiveFile)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	}

	response.OkWithMessage("创建成功", c)

}
